import { useState } from 'react';
import { Form, Input, Button, Tabs, message } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, LeftCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { registerApi, userLoginApi } from '@/api/user';
import useUserInfoStore from '@/store/userInfoStore';
interface LoginForm {
  phone: string;
  password: string;
}

interface RegisterForm {
  user_name: string;
  password: string;
  phone: string;
}
/**
 * 登录页面
 * @returns
 */
const Login = () => {
  const navigate = useNavigate();
  const [loginForm] = Form.useForm<LoginForm>();
  const [registerForm] = Form.useForm<RegisterForm>();
  const [activeTab, setActiveTab] = useState<'login' | 'register'>('login');
  const { setUserInfo, setToken } = useUserInfoStore();

  // 登陆逻辑
  const handleLogin = async (values: LoginForm) => {
    await loginForm.validateFields();
    const user = values;
    const res = await userLoginApi(user);
    // 请求码为 200 则登录成功
    if (res.code === 200) {
      localStorage.setItem('token', res.data.token);
      localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo));
      message.open({
        type: 'success',
        content: '登录成功！',
      });
      setUserInfo(res.data.userInfo);
      setToken(res.data.token);
      // 路由跳转到首页
      navigate('/');
    } else {
      message.open({
        type: 'error',
        content: '登录失败，请重试！',
      });
    }
  };

  // 注册逻辑
  const handleRegister = async (values: RegisterForm) => {
    // 这里添加注册逻辑
    await registerApi(values).then((res) => {
      if (res.code === 200) {
        // 将用户信息存储到本地存储中
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo));
        // 消息弹窗
        message.open({
          type: 'success',
          content: '注册成功！',
        });
        // 将用户信息存储到 store 中
        setUserInfo(res.data.userInfo);
        setToken(res.data.token);
        // 路由跳转到首页
        navigate('/');
      } else {
        // 注册失败消息提示
        message.open({
          type: 'error',
          content: '注册失败，请重试！',
        });
      }
    });
  };

  const items = [
    {
      key: 'login',
      label: '登录',
      children: (
        <Form
          form={loginForm}
          name="login"
          onFinish={handleLogin}
          className="mt-4"
          initialValues={{
            phone: '18888888888',
            password: '123123',
          }}
        >
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号！' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号！',
              },
            ]}
          >
            <Input
              prefix={<PhoneOutlined />}
              placeholder="手机号"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="w-full h-10 bg-emerald-600 hover:bg-emerald-700 rounded-lg !border-none"
            >
              登录
            </Button>
          </Form.Item>
          <div className="flex justify-between text-sm">
            <a style={{ color: '#10b981' }}>忘记密码？</a>
            <a style={{ color: '#10b981' }}>您是管理员？</a>
          </div>
        </Form>
      ),
    },
    {
      key: 'register',
      label: '注册',
      children: (
        <Form<RegisterForm>
          form={registerForm}
          name="register"
          onFinish={handleRegister}
          className="mt-4"
        >
          <Form.Item
            name="user_name"
            rules={[{ required: true, message: '请输入用户名！' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号！' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号！',
              },
            ]}
          >
            <Input
              prefix={<PhoneOutlined />}
              placeholder="手机号"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码！' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致！'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
              size="large"
              className="rounded-lg !border-gray-300 hover:!border-emerald-500 focus:!border-emerald-500 focus:!shadow-[0_0_0_2px_rgba(16,185,129,0.1)]"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="w-full h-10 bg-emerald-600 hover:bg-emerald-700 rounded-lg !border-none"
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      ),
    },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-emerald-800 via-emerald-700 to-emerald-600 flex items-center justify-center p-4">
      <div className="w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        {/* 顶部装饰 */}
        <div className="h-2 bg-gradient-to-r from-emerald-400 to-emerald-600"></div>
        {/* Logo区域 */}
        <div className="text-center pt-8 pb-4 relative">
          <div
            className="absolute top-2 left-2 cursor-pointer"
            onClick={() => navigate('/')}
          >
            <LeftCircleOutlined style={{ fontSize: '30px', color: '#10b981' }} />
          </div>
          <div className="w-16 h-16 bg-emerald-100 rounded-full mx-auto flex items-center justify-center mb-4">
            <span className="text-emerald-700 text-3xl font-bold">菌</span>
          </div>
          <h2 className="text-2xl font-bold text-gray-800">欢迎来到野生菌平台</h2>
          <p className="text-gray-500 mt-2">探索云南野生菌的奥秘</p>
        </div>

        {/* 表单区域 */}
        <div className="p-8 pt-4">
          <Tabs
            defaultActiveKey={activeTab}
            onChange={(key) => setActiveTab(key as 'login' | 'register')}
            centered
            className="login-tabs"
            items={items}
          />
        </div>

        {/* 底部信息 */}
        <div className="text-center pb-6 text-sm text-gray-500">
          <p>
            登录即代表同意
            <a className="text-emerald-600 hover:text-emerald-700 !no-underline">用户协议</a> 和
            <a className="text-emerald-600 hover:text-emerald-700 !no-underline">隐私政策</a>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;
